import { defineStore } from 'pinia';
// import { IUserPlaylist } from '@/models/userPlaylist';
// import { getLikelist, getUserPlaylist, likeSong } from '@/api/api';
import { ElMessage } from 'element-plus';
import { Login, getLikeList, addLike, deleteLike } from '@/api';
import router from '@/router';
export const useUserStore = defineStore('user', {
	state: () => {
		return {
			userInfo:null,
			userId: 0,
			songLikes: [],
			mvLikes: [],
			songListLikes: [],
			cookie: '',
			isLogin: false,
		};
	},
	getters: {
		// isLogin: (state: any) => {
		// 	return state.profile?.userId > 0;
		// },
	},
	actions: {
        async Login(userData:any) {
            const res = await Login(userData);
			console.log(res);
			
            if(res){
				this.userInfo = res
                this.isLogin = true;
                this.userId = res.id;
				this.songLikes = await getLikeList({userId:this.userId,type:1});  // 获取
				this.songListLikes = await getLikeList({userId:this.userId,type:2});
				this.mvLikes = await getLikeList({userId:this.userId,type:3});
				return true;
            }else{
                ElMessage.error('密码错误');
				return false;
            }
         },
		 //修改了数据
		 changeUserData(res:any){
			this.userInfo = res
		 },
		// 获取我的歌单
		// async getPlaylist(userId: number) {
		// 	this.playlist = await getUserPlaylist(userId);
		// },

		// 获取喜欢音乐列表
		// async getLikeList(userId: number) {
		// 	const { code, ids } = await getLikelist(userId);
		// 	if (code == 200) {
		// 		this.likes = ids;
		// 	} else {
		// 		ElMessage.error('登录过期，请重新登录！');
		// 	}
		// },

		// 音乐添加收藏/取消收藏
		async MusicList(type:number, likeId: number) {
			let isLike, result, list:Array<number>;
			
			if(type == 1){
				list = this.songLikes;
			}else if(type == 2){
				list = this.songListLikes;
			}else{
				list = this.mvLikes;
			}
			
			isLike = list.indexOf(likeId) == -1;
			//let msg = isLike ? '喜欢歌曲' : '取消喜欢';
			if(isLike){
				const res = await addLike({type, userId:this.userId, likeId});
				if(res){
					ElMessage.success('添加收藏成功');
					result = await getLikeList({type, userId: this.userId});
					list.length = 0
					for (let index = 0; index < result.length; index++) {
						if(type == 3){
							list.push(result[index].mvId)
						}else{
							list.push(result[index].id)
						}
					}					
					console.log("喜欢",this.mvLikes)
				}else{
					ElMessage.error('添加收藏失败');
				}
			}else{
				const res = await deleteLike({type, userId:this.userId, likeId});
				if(res){
					ElMessage.success('取消收藏成功');
					result = await getLikeList({type, userId: this.userId});
					list.length = 0
					for (let index = 0; index < result.length; index++) {
						if(type == 3){
							list.push(result[index].mvId)
						}else{
							list.push(result[index].id)
						}
					}
				}else{
					ElMessage.error('取消收藏失败');
				}
			}
		},
	},
    persist: true
});
